package com.ff.kvm.service.impl;

import com.ff.kvm.common.dv.payment.WXPayRTDV;
import com.ff.kvm.common.dv.payment.ZFBPayRTDV;
import com.ff.kvm.common.eunm.StatusEnum;
import com.ff.kvm.common.third_util.WXPayUtil;
import com.ff.kvm.common.third_util.ZFBPayUtil;
import com.ff.kvm.common.util.ConvertUtil;
import com.ff.kvm.common.util.MyUtil;
import com.ff.kvm.common.vo.Response;
import com.ff.kvm.mall.consumer.PaymentConsumer;
import com.ff.kvm.service.PayResultService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


@Service
public class PayResultServiceImpl implements PayResultService {

    private final Logger log = LoggerFactory.getLogger(getClass());


    @Autowired
    private PaymentConsumer paymentConsumer;

    @Override
    public void wxPayRT(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            String xml = WXPayUtil.getContent(request.getInputStream(),"UTF-8");
            log.info("*************微信app支付回调参数:{}",xml);
            Map<String,String> params = ConvertUtil.xmlToMap(xml);
            if(!WXPayUtil.checkSign(params)){
                log.error("微信支付回调,签名校验失败，transaction_id:{},out_trade_no:{}",params.get("transaction_id"),params.get("out_trade_no"));
            }
            if(!params.get("return_code").equals("SUCCESS")){
                out.write("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[NO]]></return_msg></xml>");
            }
            paymentConsumer.wxPayRT(MyUtil.mapToBean(params,WXPayRTDV.class));
            out = response.getWriter();
            out.write("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[NO]]></return_msg></xml>");
        } catch (IOException e) {
            e.printStackTrace();
            out.write("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[NO]]></return_msg></xml>");

        }finally {
            if(out != null){
                out.close();
            }
        }

    }


    @Override
    public void zfbPayRT(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        Map<String,String> params = dealZFBParam(request.getParameterMap());

        try {
            out  = response.getWriter();
            if(!ZFBPayUtil.checkSign(params)){
                log.error("支付宝支付回调,签名校验失败，trade_no:{},out_trade_no:{}",params.get("trade_no"),params.get("out_trade_no"));
                out.write("failure");
            }
            if(!params.get("trade_status").equals("TRADE_FINISHED") && !params.get("trade_status").equals("TRADE_SUCCESS")){
                out.write("success");
                return;
            }
            ZFBPayRTDV zfbPayRTDV = MyUtil.mapToBean(params,ZFBPayRTDV.class);
            log.info(".............支付宝app支付回调参数:{}",MyUtil.toJSON(zfbPayRTDV));
            Response<Boolean> rep = paymentConsumer.zfbPayRT(zfbPayRTDV);
            if(!rep.getCode().equals(StatusEnum.SUCCESS.code())){
                out.write("failure");
            }else{
                out.write("success");
            }
        } catch (IOException e) {
            e.printStackTrace();
            out.write("success");
        }finally {
            if(out != null){
                out.close();
            }
        }



    }

    private Map<String, String> dealZFBParam(Map<String, String[]> parameterMap) {
        Map<String,String> params = new HashMap<>();
        for (Iterator iter = parameterMap.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) parameterMap.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }

}
